import { VxeUI } from 'vxe-pc-ui';
import { ElInput, ElTag } from 'element-plus';
import { getNestedPropertyValue } from './utils';

/**
 * 获取属性值的通用函数
 * @param {string} attrName - 属性名
 * @param {*} defaultValue - 默认值
 * @param {Object} sources - 属性来源对象数组
 * @returns {*} 属性值
 */
const getAttributeValue = (attrName, defaultValue, ...sources) => {
  for (const source of sources) {
    if (source && source[attrName] !== undefined) {
      return source[attrName];
    }
  }
  return defaultValue;
};

/**
 * 格式化显示值的函数
 * @param {*} value - 原始值
 * @param {Object} renderOpts - 渲染选项
 * @param {Object} props - 属性对象
 * @param {Object} attrs - 特性对象
 * @returns {string} 格式化后的显示值
 */
const formatDisplayValue = (value, renderOpts, props = {}, attrs = {}) => {
  if (value === null || value === undefined || value === '') {
    return '-';
  }

  // 获取格式化配置
  const formatter = getAttributeValue(
    'formatter',
    null,
    props,
    attrs,
    renderOpts,
  );
  const maxLength = getAttributeValue(
    'maxLength',
    null,
    props,
    attrs,
    renderOpts,
  );
  const showPassword = getAttributeValue(
    'showPassword',
    false,
    props,
    attrs,
    renderOpts,
  );

  let displayValue = String(value);

  // 密码类型处理
  if (showPassword) {
    displayValue = '*'.repeat(displayValue.length);
  }

  // 长度限制处理
  if (maxLength && displayValue.length > maxLength) {
    displayValue = displayValue.substring(0, maxLength) + '...';
  }

  // 自定义格式化函数
  if (formatter && typeof formatter === 'function') {
    displayValue = formatter(value);
  }

  return displayValue;
};

/**
 * 渲染输入框显示模式的通用函数
 * @param {Object} renderOpts - 渲染选项
 * @param {Object} params - 参数对象
 * @returns {JSX.Element} 渲染结果
 */
const renderInputDisplay = (renderOpts, params) => {
  // 确定有效的数据和列上下文
  const effectiveData = params?.row || renderOpts.row || renderOpts.data || {};
  const effectiveColumn = params?.column || renderOpts.column || {};

  // 获取字段名
  const field =
    effectiveColumn.field || effectiveColumn.property || params?.field;

  if (!field) {
    console.warn('ElInputRender: Missing field identifier in display mode');
    return <span>-</span>;
  }

  // 获取当前值
  const value = effectiveData[field];

  // 获取配置信息
  const props = renderOpts.props || {};
  const attrs = renderOpts.attrs || {};

  // 格式化显示值
  const displayValue = formatDisplayValue(value, renderOpts, props, attrs);

  // 获取样式配置
  const displayStyle = getAttributeValue(
    'displayStyle',
    {},
    props,
    attrs,
    renderOpts,
  );
  const className = getAttributeValue(
    'displayClass',
    '',
    props,
    attrs,
    renderOpts,
  );

  // 返回显示元素
  return (
    <span
      class={className}
      style={{
        padding: '4px 8px',
        minHeight: '20px',
        display: 'inline-block',
        ...displayStyle,
      }}
    >
      {displayValue}
    </span>
  );
};

/**
 * 通用渲染逻辑函数（用于编辑模式）
 * @param {Object} renderOpts - 渲染选项
 * @param {Object} params - 参数对象
 * @returns {JSX.Element} 渲染结果
 */
const renderElInput = (renderOpts, params) => {
  // 确定有效的数据和项上下文
  const effectiveData = params?.row || params?.data || renderOpts.data || {};
  const effectiveItem = params?.item || renderOpts.item || {};
  const effectiveColumn = params?.column || {};

  // 确定字段名
  const field =
    params?.field ||
    effectiveColumn.field ||
    effectiveItem.field ||
    renderOpts.field;

  if (!field) {
    console.error('ElInputRender: Missing field identifier in edit mode');
    return null;
  }

  // 获取当前值
  // const value = effectiveData[field];
  // 获取当前值，使用辅助函数支持多层属性访问
  const value = getNestedPropertyValue(effectiveData, field);

  // 从effectiveItem中获取配置信息
  const itemRender = effectiveItem.itemRender || {};
  const props = itemRender.props || renderOpts.props || {};
  const attrs = itemRender.attrs || renderOpts.attrs || {};
  const events = itemRender.events || renderOpts.events || {};

  const title = effectiveColumn.title || effectiveItem.title || '';

  // 事件处理器
  const updateValue = (val) => {
    // 更新数据
    if (params?.row) {
      params.row[field] = val;
    } else if (params?.data) {
      params.data[field] = val;
    } else if (renderOpts.data) {
      renderOpts.data[field] = val;
    }

    // 触发原始事件
    events.input?.(val, effectiveData, params || renderOpts);
  };

  const handleChange = (val) => {
    // 触发change事件
    events.change?.(val, effectiveData, params || renderOpts);
  };

  const handleFocus = (event) => {
    // 触发focus事件
    events.focus?.(event, effectiveData, params || renderOpts);
  };

  const handleBlur = (event) => {
    // 触发blur事件
    events.blur?.(event, effectiveData, params || renderOpts);
  };

  const handleClear = () => {
    // 清空值
    updateValue('');
    // 触发clear事件
    events.clear?.(effectiveData, params || renderOpts);
  };

  // 构建输入框属性
  const inputProps = {
    modelValue: value,
    'onUpdate:modelValue': updateValue,
    onChange: handleChange,
    onFocus: handleFocus,
    onBlur: handleBlur,
    onClear: handleClear,

    // 基础属性
    type: getAttributeValue(
      'type',
      'text',
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    disabled: getAttributeValue(
      'disabled',
      renderOpts.disabled || false,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    readonly: getAttributeValue(
      'readonly',
      false,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    placeholder: getAttributeValue(
      'placeholder',
      `请输入${title}`,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),

    // 尺寸和样式
    size: getAttributeValue(
      'size',
      undefined,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    style: getAttributeValue('style', {}, props, attrs, itemRender, renderOpts),
    class: getAttributeValue('class', '', props, attrs, itemRender, renderOpts),

    // 功能属性
    clearable: getAttributeValue(
      'clearable',
      false,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    showPassword: getAttributeValue(
      'showPassword',
      false,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    showWordLimit: getAttributeValue(
      'showWordLimit',
      false,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    maxlength: getAttributeValue(
      'maxlength',
      null,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    minlength: getAttributeValue(
      'minlength',
      null,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),

    // 前缀后缀
    prefixIcon: getAttributeValue(
      'prefixIcon',
      '',
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    suffixIcon: getAttributeValue(
      'suffixIcon',
      '',
      props,
      attrs,
      itemRender,
      renderOpts,
    ),

    // textarea特有属性
    rows: getAttributeValue('rows', 2, props, attrs, itemRender, renderOpts),
    autosize: getAttributeValue(
      'autosize',
      false,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    resize: getAttributeValue(
      'resize',
      'vertical',
      props,
      attrs,
      itemRender,
      renderOpts,
    ),

    // 验证相关
    validateEvent: getAttributeValue(
      'validateEvent',
      true,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),

    // 其他属性
    autocomplete: getAttributeValue(
      'autocomplete',
      'off',
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    name: getAttributeValue(
      'name',
      field,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
    label: getAttributeValue('label', '', props, attrs, itemRender, renderOpts),
    tabindex: getAttributeValue(
      'tabindex',
      null,
      props,
      attrs,
      itemRender,
      renderOpts,
    ),
  };

  // 过滤掉值为null或undefined的属性
  const filteredProps = Object.fromEntries(
    Object.entries(inputProps).filter(
      ([key, value]) => value !== null && value !== undefined,
    ),
  );

  // 返回ElInput组件
  return <ElInput {...filteredProps} />;
};

// 注册支持多种上下文的渲染器
VxeUI.renderer.add('RaElInputRender', {
  // 表格单元格编辑模式
  renderTableEdit(renderOpts, params) {
    return renderElInput(renderOpts, params);
  },

  // 表格单元格显示模式
  renderTableCell(renderOpts, params) {
    return renderInputDisplay(renderOpts, params);
  },

  // 表单项目渲染
  renderItemContent(renderOpts, params) {
    return renderElInput(renderOpts, params);
  },

  // 默认显示模式（与renderTableCell相同）
  renderDefault(renderOpts, params) {
    return renderInputDisplay(renderOpts, params);
  },
});

export default 'RaElInputRender';
